﻿using System;

namespace WindowsPhoneEssentials.Diagnostics
{
    /// <summary>
    /// Stopwatch is used to measure the general performance of Silverlight functionality. Silverlight
    /// does not currently provide a high resolution timer as is available in many operating systems,
    /// so the resolution of this timer is limited to milliseconds. This class is best used to measure
    /// the relative performance of functions over many iterations.
    /// 
    /// FROM: http://www.wiredprairie.us/blog/index.php/archives/723
    /// </summary>
    public sealed class Stopwatch
    {
        private long startTick;
        private long elapsed;

        /// <summary>
        /// Completely resets and deactivates the timer.
        /// </summary>
        public void Reset()
        {
            elapsed = 0;
            IsRunning = false;
            startTick = 0;
        }

        /// <summary>
        /// Begins the timer.
        /// </summary>
        public void Start()
        {
            if (IsRunning) return;
            startTick = GetCurrentTicks();
            IsRunning = true;
        }

        /// <summary>
        /// Stops the current timer.
        /// </summary>
        public void Stop()
        {
            if (!IsRunning) return;
            elapsed += GetCurrentTicks() - startTick;
            IsRunning = false;
        }

        /// <summary>
        /// Gets a value indicating whether the instance is currently recording.
        /// </summary>
        public bool IsRunning { get; private set; }

        /// <summary>
        /// Gets the Elapsed time as a Timespan.
        /// </summary>
        public TimeSpan Elapsed
        {
            get { return TimeSpan.FromMilliseconds(ElapsedMilliseconds); }
        }

        /// <summary>
        /// Gets the Elapsed time as the total number of milliseconds.
        /// </summary>
        public long ElapsedMilliseconds
        {
            get { return GetCurrentElapsedTicks() / TimeSpan.TicksPerMillisecond; }
        }

        /// <summary>
        /// Gets the Elapsed time as the total number of ticks (which is faked
        /// as Silverlight doesn't have a way to get at the actual "Ticks")
        /// </summary>
        public long ElapsedTicks
        {
            get { return GetCurrentElapsedTicks(); }
        }

        private long GetCurrentElapsedTicks()
        {
            return elapsed + (IsRunning ? (GetCurrentTicks() - startTick) : 0);
        }

        private static long GetCurrentTicks()
        {
            return Environment.TickCount * TimeSpan.TicksPerMillisecond;
        }
    }
}